﻿
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.Onlines.Dtos;
using KDS.Mes.Dto;
using KDS.Mes.Authorization;
using KDS.Mes.Mes.Lines;
using KDS.Mes.Mes.Styles;
using KDS.Mes.Mes.Cartypes;
using KDS.Mes.Mes.AlcCodes;

namespace KDS.Mes.Mes.Onlines
{
    /// <summary>
    /// 上线信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Plan_Onlines)]
    public class OnlineAppService : MesAppServiceBase, IOnlineAppService
    {
        private readonly IRepository<Online, int> _onlineRepository;
        private readonly IOnlineListExcelExporter _onlineListExcelExporter;
        private readonly IRepository<Line, int> _lineRepository;
        private readonly IRepository<Style, int> _styleRepository;
        private readonly IRepository<Cartype, int> _cartypeRepository;
        private readonly IRepository<AlcCode, int> _alcCodeRepository;


        private readonly OnlineManage _onlineManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public OnlineAppService(IRepository<Online, int> onlineRepository,
                                OnlineManage onlineManage,
                                IOnlineListExcelExporter onlineListExcelExporter,
                                IRepository<Line, int> lineRepository,
                                 IRepository<Style, int> styleRepository,
                                  IRepository<AlcCode, int> alcCodeRepository,
            IRepository<Cartype, int> cartypeRepository
  )
        {
            _onlineRepository = onlineRepository;
            _onlineManage = onlineManage;
            _onlineListExcelExporter = onlineListExcelExporter;
            _lineRepository = lineRepository;
            _styleRepository = styleRepository;
            _alcCodeRepository = alcCodeRepository;
            _cartypeRepository = cartypeRepository;
        }

        #region 上线信息管理

        public PagedResultDto<OnlineListDto> GetPagedOnlines(GetOnlineInput input)
        {

            ////初步过滤
            var query = from online in _onlineRepository.GetAll()
                                        .WhereIf(!input.SeatID.IsNullOrEmpty(), u => u.SeatID == input.SeatID)
                                        .WhereIf(!input.Time1.ToString().IsNullOrEmpty(),u=> u.OnlineTime >=input.Time1)
                                        .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.OnlineTime <= input.Time2)
                        join ln in _lineRepository.GetAll().WhereIf(!input.LineId.IsNullOrEmpty(), u => u.Id.ToString() == input.LineId) on online.LineId equals ln.Id
                        join alc in _alcCodeRepository.GetAll() on online.SeatID.Substring(0,4) equals alc.ALCCode
                        join st in _styleRepository.GetAll().WhereIf(!input.StyleId.IsNullOrEmpty(), u => u.Id.ToString() == input.StyleId) on alc.StyleId equals st.Id
                        join ct in _cartypeRepository.GetAll().WhereIf(!input.CartypeId.IsNullOrEmpty(), u => u.Id.ToString() == input.CartypeId) on st.CartypeId equals ct.Id
                        
                        select new
                        {
                            online
                        };
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderByDescending(x => x.online.Id) : query.OrderByDescending(t => t.online.Id);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();

            return new PagedResultDto<OnlineListDto>(
             tasksCount,
             taskList.Select(item =>
             {
                 var dto = item.online.MapTo<OnlineListDto>();
                 return dto;
             }).ToList());




            ////初步过滤
            //var query = _onlineRepository.GetAll();
            ////排序
            //query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.Id);
            ////获取总数
            //var tasksCount = query.Count();
            ////默认的分页方式
            ////var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            ////ABP提供了扩展方法PageBy分页方式
            //var taskList = query.PageBy(input).ToList();
            //return new PagedResultDto<OnlineListDto>(tasksCount, taskList.MapTo<List<OnlineListDto>>());
        }

        /// <summary>
        /// 根据查询条件获取上线信息分页列表
        /// </summary>
        public async Task<PagedResultDto<OnlineListDto>> GetPagedOnlinesAsync(GetOnlineInput input)
        {

            var query = _onlineRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var onlineCount = await query.CountAsync();

            var onlines = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var onlineListDtos = onlines.MapTo<List<OnlineListDto>>();
            return new PagedResultDto<OnlineListDto>(
            onlineCount,
            onlineListDtos
            );
        }

        /// <summary>
        /// 通过Id获取上线信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetOnlineForEditOutput> GetOnlineForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetOnlineForEditOutput();

            OnlineEditDto onlineEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _onlineRepository.GetAsync(input.Id.Value);
                onlineEditDto = entity.MapTo<OnlineEditDto>();
            }
            else
            {
                onlineEditDto = new OnlineEditDto();
            }

            output.Online = onlineEditDto;
            output.Lines = _lineRepository.GetAllList()
               .Select(c => new ComboboxItemDto(c.Id.ToString(), c.LineName) { IsSelected = output.Online.LineId == c.Id })
               .ToList();
            return output;
        }


        /// <summary>
        /// 通过指定id获取上线信息ListDto信息
        /// </summary>
        public async Task<OnlineListDto> GetOnlineByIdAsync(EntityDto<int> input)
        {
            var entity = await _onlineRepository.GetAsync(input.Id);

            return entity.MapTo<OnlineListDto>();
        }







        /// <summary>
        /// 新增或更改上线信息
        /// </summary>
        public async Task CreateOrUpdateOnlineAsync(CreateOrUpdateOnlineInput input)
        {
            if (input.OnlineEditDto.Id.HasValue)
            {
                await UpdateOnlineAsync(input.OnlineEditDto);
            }
            else
            {
                await CreateOnlineAsync(input.OnlineEditDto);
            }
        }

        /// <summary>
        /// 新增上线信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_Onlines_Create)]
        public virtual async Task<OnlineEditDto> CreateOnlineAsync(OnlineEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<Online>();

            entity = await _onlineRepository.InsertAsync(entity);
            return entity.MapTo<OnlineEditDto>();
        }

        /// <summary>
        /// 编辑上线信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_Onlines_Edit)]
        public virtual async Task UpdateOnlineAsync(OnlineEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _onlineRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _onlineRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除上线信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_Onlines_Delete)]
        public async Task DeleteOnlineAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _onlineRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除上线信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_Onlines_Delete)]
        public async Task BatchDeleteOnlineAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _onlineRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion


        #region 上线信息的Excel导出功能


        public async Task<FileDto> GetOnlineToExcel(GetOnlineInput input)
        {
            var entities = await _onlineRepository.GetAll().
               WhereIf(!input.SeatID.IsNullOrEmpty(), u => u.SeatID == input.SeatID)
                                    .WhereIf(!input.Time1.ToString().IsNullOrEmpty(), u => u.OnlineTime >= input.Time1)
                                    .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.OnlineTime <= input.Time2).ToListAsync();
         

            var dtos = entities.MapTo<List<OnlineListDto>>();

            var fileDto = _onlineListExcelExporter.ExportOnlineToFile(dtos);



            return fileDto;
        }
      


        #endregion










    }
}
